<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="设备名称" prop="eqName">
        <el-input
          v-model="queryParams.eqName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="设备型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入设备型号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['testequipment:test-equipment:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
    >
      <el-table-column label="编号" align="center" prop="id" sortable /> <!-- 新增sortable支持表格排序 -->
      <el-table-column label="设备名称" align="center" prop="eqName" />
      <el-table-column label="设备型号" align="center" prop="model" />
      <el-table-column label="存放位置" align="center" prop="storageLocation" />
      <el-table-column label="操作人" align="center" prop="updater" />
      <el-table-column
        label="操作时间"
        align="center"
        prop="updateTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="220px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleView(scope.row)"
            v-hasPermi="['testequipment:test-equipment:query']"
          >
            查看
          </el-button>
          <el-button
            link
            type="success"
            @click="handleInStorage(scope.row)"
            v-hasPermi="['testequipment:test-equipment:update']"
            :loading="inStorageLoading[scope.row.id]"
          >
            入库
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import { TestEquipmentApi, TestEquipmentMyUse } from '@/api/testequipment/testequipment'

/** 我的已出库设备使用记录 列表 */
defineOptions({ name: 'MyEquipmentUse' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<TestEquipmentMyUse[]>([]) // 类型改为 TestEquipmentMyUse
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  eqName: undefined,
  model: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const inStorageLoading = ref<Record<number, boolean>>({}) // 入库按钮加载状态（防止重复点击）

/** 查询列表 - 调用最新的我的已出库接口 */
const getList = async () => {
  loading.value = true
  try {
    const response = await TestEquipmentApi.getMyEquipmentUsePage(queryParams)
    list.value = response.list || []
    total.value = response.total || 0
    console.log('我的已出库设备数据:', response)
  } catch (error) {
    console.error('获取我的已出库设备失败:', error)
    message.error('获取数据失败，请重试')
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 查看详情操作 */
const handleView = (row: TestEquipmentMyUse) => {
  const detailInfo = {
    id: row.id,
    eqName: row.eqName,
    model: row.model,
    storageLocation: row.storageLocation,
    updater: row.updater,
    updateTime: row.updateTime,
  }
  
  ElMessageBox.alert(
    `
      <div class="detail-info">
        <h4>我的已出库设备详情</h4>
        <table style="width: 100%; border-collapse: collapse; font-size: 14px;">
          <tr style="border-bottom: 1px solid #eee; height: 40px;">
            <td style="padding: 0 10px; width: 30%; font-weight: 500; text-align: right;">编号：</td>
            <td style="padding: 0 10px;">${detailInfo.id || '-'}</td>
          </tr>
          <tr style="border-bottom: 1px solid #eee; height: 40px;">
            <td style="padding: 0 10px; font-weight: 500; text-align: right;">设备名称：</td>
            <td style="padding: 0 10px;">${detailInfo.eqName || '-'}</td>
          </tr>
          <tr style="border-bottom: 1px solid #eee; height: 40px;">
            <td style="padding: 0 10px; font-weight: 500; text-align: right;">设备型号：</td>
            <td style="padding: 0 10px;">${detailInfo.model || '-'}</td>
          </tr>
          <tr style="border-bottom: 1px solid #eee; height: 40px;">
            <td style="padding: 0 10px; font-weight: 500; text-align: right;">存放位置：</td>
            <td style="padding: 0 10px;">${detailInfo.storageLocation || '-'}</td>
          </tr>
          <tr style="border-bottom: 1px solid #eee; height: 40px;">
            <td style="padding: 0 10px; font-weight: 500; text-align: right;">操作人：</td>
            <td style="padding: 0 10px;">${detailInfo.updater || '-'}</td>
          </tr>
          <tr style="height: 40px;">
            <td style="padding: 0 10px; font-weight: 500; text-align: right;">操作时间：</td>
            <td style="padding: 0 10px;">${detailInfo.updateTime ? dateFormatter(detailInfo.updateTime) : '-'}</td>
          </tr>
        </table>
      </div>
    `,
    '详情',
    {
      dangerouslyUseHTMLString: true,
      customClass: 'detail-dialog',
      confirmButtonText: '关闭',
      cancelButtonText: '',
      showCancelButton: false,
      width: '550px'
    }
  )
}

/** 入库操作：修改设备使用状态为未出库（0）+ 写入入库操作记录 */
const handleInStorage = async (row: TestEquipmentMyUse) => {
  // 1. 防止重复点击：设置当前按钮加载状态
  inStorageLoading.value[row.id] = true
  try {
    // 2. 二次确认弹窗
    await ElMessageBox.confirm(
      `确认将【${row.eqName || '未知设备'}】（编号：${row.id}）入库吗？`,
      '确认入库',
      {
        confirmButtonText: '确认入库',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true // 支持弹窗拖拽
      }
    )

    // 3. 调用后端入库接口（核心逻辑：状态改为0 + 写入操作记录）
    await TestEquipmentApi.updateTestEquipmentStatus({
      id: row.id,
      useStatus: 0 // 0=未出库，与后端一致
    })
 
    // 4. 操作成功反馈
    ElMessage.success(`设备【${row.eqName || '未知设备'}】入库成功！`)
    
    // 5. 刷新列表：入库后设备从"已出库"列表移除
    getList()
  } catch (error: any) {
    // 6. 错误处理（区分取消操作和真实错误）
    if (error.name !== 'CanceledError') {
      console.error(`设备入库失败（ID：${row.id}）:`, error)
      ElMessage.error(`入库失败：${error.message || '服务器异常，请重试'}`)
    }
  } finally {
    // 7. 恢复按钮状态
    inStorageLoading.value[row.id] = false
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await TestEquipmentApi.exportMyEquipmentUse({
      eqName: queryParams.eqName,
      model: queryParams.model,
    })
    download.excel(data, '我的已出库设备记录表.xls')
  } catch (error) {
    console.error('导出我的已出库设备失败:', error)
    message.error('导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

/** 初始化加载数据 */
onMounted(() => {
  getList()
})
</script>

<style scoped>
.detail-dialog .el-message-box__content {
  padding: 20px !important;
}
.detail-info h4 {
  margin: 0 0 15px 0;
  color: #1989fa;
  font-size: 16px;
  text-align: center;
}
/* 优化表格排序样式 */
.el-table__sort-indicator {
  color: #1989fa;
}
</style>